package com.sumfun.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sumfun.blog.model.domain.TimeLine;
import com.sumfun.blog.model.dto.TimeLineDto;
import com.sumfun.blog.service.TimeLineService;
import com.sumfun.blog.mapper.TimeLineMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author 17337
* @description 针对表【time_line】的数据库操作Service实现
* @createDate 2025-02-11 14:52:22
*/
@Service
public class TimeLineServiceImpl extends ServiceImpl<TimeLineMapper, TimeLine>
    implements TimeLineService{

    public List<TimeLineDto> getTimeLineTree() {
        // 查询所有parentId为0的顶级时间线项
        QueryWrapper<TimeLine> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", 0);
        queryWrapper.orderByDesc("record_time");
        List<TimeLine> topLevelTimeLines = this.list(queryWrapper);

        // 递归构建树形结构
        List<TimeLineDto> tree = topLevelTimeLines.stream()
                .map(this::buildTreeNode)
                .collect(Collectors.toList());

        return tree;
    }

    private TimeLineDto buildTreeNode(TimeLine timeLine) {
        TimeLineDto node = new TimeLineDto();
        node.setId(timeLine.getId());
        node.setText(timeLine.getText());
        node.setImageurl(timeLine.getImageurl());
        node.setCreateTime(timeLine.getCreateTime());
        node.setUpdateTime(timeLine.getUpdateTime());
        node.setRecordTime(timeLine.getRecordTime());
        node.setParentId(timeLine.getParentId());

        // 递归查询子节点
        QueryWrapper<TimeLine> childQueryWrapper = new QueryWrapper<>();
        childQueryWrapper.eq("parent_id", timeLine.getId());
        childQueryWrapper.orderByDesc("record_time");
        List<TimeLine> childTimeLines = this.list(childQueryWrapper);
        node.setChildren(childTimeLines.stream()
                .map(this::buildTreeNode)
                .collect(Collectors.toList()));

        return node;
    }

}




